// pages/contactList/contactList.js
const app = getApp()
import {
  get_open_id,
  user_login
} from "../../utils/api.js";

var utils = require('../../utils/util.js');
var page = 1;
var selectedNews = false;
var newsList = [];
const {
  getTimeSeconds
} = utils

Page({
  /**
   * 页面的初始数据
   */
  data: {
    haveTap: 1, // 1: 可以点击 0：不可点击
    TaskShow: 0,
    userInfo: {},
    delBtnWidth: 90,
    setInter: '',
    unreadnum: 0,
    unreadnum2: 0,
    btuBottom: 0,
    fxTaskShow: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this
    if (options.coming_status != undefined) {
      that.setData({
        fxTaskShow: 1
      });
    }
  },
  // 检测是否需要登录
  checkUserInfo: function() {
    const that = this
    let openid = wx.getStorageSync('openid')
    if (openid) {
      app.globalData.openid = openid
      that.setData({
        openid,
      })
      let url = '/user_api/getInfoByOpenID';
      app.HttpPostSend(
        url, {
          openid: openid,
        },

        function(result_data) {
          if (result_data.msg != "success") {
            app.showTipMsg(result_data.msg);
          } else {
            if (!!result_data.data) { //如果后台有数据
              app.globalData.userInfo = {
                ...result_data.data
              }
              wx.setStorage({
                key: 'userInfo',
                data: JSON.stringify({
                  ...result_data.data
                })
              })
              that.setData({
                userInfo: result_data.data
              })
              that.getUnRead();
              that.getContactList();
              that.wssInit();
            } else { //如果后台无数据
              wx.login({
                success(res) {
                  let params = {
                    code: res.code
                  }
                  app.HttpGetSend(get_open_id, params, function(result) {
                    if (result.msg != "success") {
                      app.showTipMsg(result.msg);
                    } else {
                      app.globalData.openid = result.data.openid.openid;
                      app.globalData.userInfo = result.data.userinfo;
                      wx.setStorage({
                        key: 'openid',
                        data: result.data.openid.openid
                      })
                      that.setData({
                        openid: result.data.openid.openid
                      })
                      that.setData({
                        TaskShow: 1,
                        openid: result.data.openid.openid
                      })
                      that.wssInit();
                    }
                  })
                }
              })
            }
          }
        })
    } else {
      wx.login({
        success(res) {
          let params = {
            code: res.code
          }
          app.HttpGetSend(get_open_id, params, function(result) {
            if (result.msg != "success") {
              app.showTipMsg(result.msg);
            } else {
              app.globalData.openid = result.data.openid.openid;
              app.globalData.userInfo = result.data.userinfo;
              wx.setStorage({
                key: 'openid',
                data: result.data.openid.openid
              })
              that.setData({
                openid: result.data.openid.openid
              })
              that.setData({
                TaskShow: 1,
                openid: result.data.openid.openid
              })
              that.wssInit();
            }
          })
        }
      })
    }

    let systemInfo = wx.getSystemInfoSync()
    app.globalData.systemInfo = systemInfo
    this.setData({
      systemInfo
    })

  },

  // 获取用户信息
  bindGetUserInfo: function(e) {
    const that = this
    let userInfo = e.detail.userInfo
    try {
      app.HttpPostSend(
        user_login, {
          openid: that.data.openid,
          username: userInfo.nickName,
          logo: userInfo.avatarUrl,
          sex: userInfo.gender
        },
        function(result_data) {
          if (result_data.msg != "success") {
            app.showTipMsg(result_data.msg);
          } else {
            app.globalData.authSettingUser = 1;
            let userInfo = {
              ...result_data.data
            }
            app.globalData.userInfo = userInfo
            wx.setStorage({
              key: 'userInfo',
              data: JSON.stringify(userInfo)
            })
            that.setData({
              TaskShow: 0,
              haveTap: 1,
              userInfo: userInfo
            })
            that.getUnRead();
            that.getContactList();
          }
        })
    } catch (error) {

    }
  },

  //获取雷达未读数量
  getUnRead: function() {
    var that = this;
    var url2 = '/log_api/logReadNum';
    var params2 = {
      uid: app.globalData.userInfo.id
    };
    app.HttpGetSend(url2, params2, function(res) {
      if (res.msg != "success") {
        app.showTipMsg(res.msg);
      } else {
        var count = res.data;
        if (count > 99) {
          count = 99;
        }
        that.setData({
          unreadnum: count
        })

        //获取聊天未读数量
        var url3 = '/chat_api/getReadNum';
        var params3 = {
          uid: app.globalData.userInfo.id
        };
        app.HttpGetSend(url3, params3, function(res) {
          if (res.msg != "success") {
            app.showTipMsg(res.msg);
          } else {
            var count = res.data;
            if (count > 99) {
              count = 99;
            }
            that.setData({
              unreadnum2: count
            })

            that.changeStatus();
          }
        });

      }
    });
  },

  //更改通知状态
  changeStatus: function() {
    const that = this;
    var url2 = '/weixin_api/updateTemplateResult';
    var params2 = {
      operatorId: that.data.userInfo.id
    };
    app.HttpGetSend(url2, params2, function(res) {
      if (res.msg != "success") {
        app.showTipMsg(res.msg);
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    selectedNews = false;
    newsList = [];
    page = 1;
    wx.getSystemInfo({
      success: res => {
        // console.log('手机信息res'+res.model)
        let modelmes = res.model;
        if (modelmes.search('iPhone X') != -1) {
          that.setData({
            btuBottom: '42rpx'
          });
        }
      }
    })
    that.checkUserInfo();
    // var that = this;
    // that.wssInit()
    //每隔五秒获取列表数据
    // that.data.setInter = setInterval(function () {
    //   //循环执行代码
    //   if (!!app.globalData.userInfo.id) {
    //     that.getContactList();
    //   }
    // }, 5000) //循环时间 这里是1秒
  },


  wssInit: function() {

    var that = this;
    that.connectWss();
    wx.onSocketClose(function() {
      console.log("居然关闭了");
      that.connectWss();
    })
    // 链接失败显示
    wx.onSocketError(function(res) {
      console.log('WebSocket连接打开失败，请检查！', res);
      that.setData({
        isOpen: false,
        statusMsg: '已断开'
      });
    });
    // 监听连接成功
    wx.onSocketOpen(function(res) {
      console.log('WebSocket连接已打开！')

      that.setData({
        isOpen: true,
        statusMsg: '已连接'
      });
      wx.sendSocketMessage({
        data: JSON.stringify({
          message: '',
          uid: app.globalData.userInfo.id,
          tuid: 0,
          p_id: 0,
          type: 1,
          is_read: 2,
          length: ''
        }),
        success: res => {

        }
      });
      // that.send(0)
      wx.onSocketMessage(function(res) {

        console.log('服务器返回消息：' + res.data)
        var re_data1 = res.data;
        var re_data = JSON.parse(re_data1); //可用此方法来转换
        if (re_data.status == 1){
          var message_list = re_data.message;
          var contactlist = that.data.contactlist;
          // console.log(message_list);
          // console.log(contactlist);
          var unreadnum2 = that.data.unreadnum2;
          var key = -1;
          for (let i in contactlist) {
            var mlist = contactlist[i].list;
            if (contactlist[i].room_id == message_list.room_id && contactlist[i].flag != message_list.flag) {
              key = i;
              if (message_list.length == 2) {
                if (message_list.type == 3) {
                  message_list.message = "[语音]";
                } else if (message_list.type == 2) {
                  message_list.message = "[图片]";
                }
              } else {
                if (message_list.type == 3) {
                  message_list.message = "[语音]";
                } else if (message_list.type == 2) {
                  message_list.message = "[图片]";
                }
              }

              contactlist[i].list = {
                'a_uid': message_list.a_uid,
                'uid': message_list.uid,
                'message': message_list.message,
                'p_id': message_list.p_id,
                'room_id': message_list.room_id,
                'create_time': message_list.create_time
              };
              contactlist[i].flag = message_list.flag;
              if (message_list.uid == app.globalData.userInfo.id){

              }else{
                contactlist[i].count = parseInt(contactlist[i].count) + parseInt(1);
                unreadnum2 = parseInt(unreadnum2) + parseInt(1);
              }
              
              

            }
          }
          console.log(unreadnum2);
          if (key >= 0) {
            var str = contactlist.splice(key, 1);
            contactlist.unshift(str[0]);
          }

          that.setData({
            contactlist: contactlist,
            unreadnum2: unreadnum2
          });
        }
        

      });
      // wx.sendSocketMessage({

      // });
    })
  },

  connectWss: function() {

    this.setData({
      statusMsg: '连接中。。。'
    });
    this.wssconnect();
  },
  wssconnect: function() {

    //Socket连接
    var sk = wx.connectSocket({
      url: 'wss://wss.51jlkj.com/server/index/index'
    })
    this.setData({
      sk: sk
    });

  },

  // 获取聊天记录列表
  getContactList: function() {
    wx.showLoading({
      title: '获取数据中',
    })
    const that = this
    var url = "/chat_api/index";
    var params = {
      uid: app.globalData.userInfo.id,
      page: page,
      page_size: 10,
    }
    app.HttpGetSend(url, params, function(res) {
      wx.hideLoading();
      if (res.msg != "success") {
        app.showTipMsg(res.msg);
      } else {
        let contactlist = res.data;
        for (var i = 0; i < contactlist.length; i++) {
          contactlist[i].count = Number(contactlist[i].count);
          if (contactlist[i].count > 99) {
            contactlist[i].count = 99;
          }
          contactlist[i].firstId = contactlist[i].list[0].id;
          for (var j = 0; j < contactlist[i].list.length; j++) {
            contactlist[i].list[j].create_time = that.timestampToTime(contactlist[i].list[j].create_time * 1000);
          }
          if (contactlist[i].list.length == 2) {

            if (contactlist[i].list[1].type == 3) {
              contactlist[i].list[1].message = "[语音]";
            } else if (contactlist[i].list[1].type == 2) {
              contactlist[i].list[1].message = "[图片]";
            }
            contactlist[i].list = contactlist[i].list[1];
          } else {

            if (contactlist[i].list[0].type == 3) {
              contactlist[i].list[0].message = "[语音]";
            } else if (contactlist[i].list[0].type == 2) {
              contactlist[i].list[0].message = "[图片]";
            }
            contactlist[i].list = contactlist[i].list[0];
          }
          contactlist[i].txtStyle = "";
          newsList.push(contactlist[i]);
        }
        console.log('contactlist:', contactlist);

        if (contactlist.length < 10) {
          selectedNews = false;
        } else {
          selectedNews = true;
          page += 1;
        }
        that.setData({
          contactlist: newsList
        })
      }
    })
  },

  timestampToTime: function(timestamp) {
    var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var Y = date.getFullYear() + '/';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '/';
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate() + "";
    var h = date.getHours() + ':';
    var m = date.getMinutes();
    if (String(m).length == 1) {
      m = "0" + m;
    }
    var s = date.getSeconds();
    return Y + M + D + " " + h + m;
  }, //转化后格式xxxx-xx-xx,

  //点击进入聊天页面
  showContactMessage: function(e) {
    var that = this
    // wx.closeSocket()
    that.data.sk.close();
    wx.onSocketClose(function() {
      console.log('Socket关闭00');
      
    });
    var id = e.currentTarget.dataset.id;
    var userid = e.currentTarget.dataset.userid;

    wx.navigateTo({
      url: '/pages/socks/socks?mid=' + userid
    })
  },

  // 打开雷达互动页面
  goRadarCenter: function() {
    const that = this
    wx.showLoading({
      mask: 'true'
    })
    var userinfo = app.globalData.userInfo
    console.log(userinfo);
    if (userinfo.type != undefined && userinfo.type == 1 && userinfo.is_shop != undefined && userinfo.is_shop == 0) {
      
      wx.switchTab({
        url: '/pages/carteShow/carteShow',
      })
    } else if (userinfo.type != undefined && userinfo.type == 2) {
     
      wx.redirectTo({
        url: '/radarPages/radarCenter/radarCenter',
        success() {
          wx.hideLoading()
        },
        fail() {
          wx.hideLoading()
        }
      })
    }

  },

  // 打开个人名片页面
  goMyCarte: function() {
    const that = this
    var userinfo = app.globalData.userInfo

    if (userinfo.type != undefined && userinfo.type == 1 && userinfo.is_shop != undefined && userinfo.is_shop == 0) {

      wx.switchTab({
        url: '/pages/carteShow/carteShow',
      })
    } else if (userinfo.type != undefined && userinfo.type == 2 ) {
      wx.redirectTo({
        url: '/pages/myCarte/myCarte'
      })
    }

  },

  // 返回名片首页
  goPerson: function() {
    const that = this
    wx.switchTab({
      url: '/pages/person/person',
    })
  },

  // 打开商品管理页面
  goManagePage: function() {
    const that = this
    if (that.data.userInfo.is_staff == 1 && that.data.userInfo.is_boss == 0) {
      app.showTipMsg('无权限');
    } else {
      var userinfo = app.globalData.userInfo

      if (userinfo.type != undefined && userinfo.type == 1 && userinfo.is_shop != undefined && userinfo.is_shop == 0) {

        wx.switchTab({
          url: '/pages/carteShow/carteShow',
        })
      } else if (userinfo.type != undefined && userinfo.type == 2) {
        wx.redirectTo({
          url: '/pages/manageGoods/manageGoods'
        })
      }
    }
    

  },

  touchS: function(e) {
    if (e.touches.length == 1) {
      this.setData({
        //设置触摸起始点水平方向位置
        startX: e.touches[0].clientX
      });
    }
  },

  touchM: function(e) {
    if (e.touches.length == 1) {
      //手指移动时水平方向位置
      var moveX = e.touches[0].clientX;
      //手指起始点位置与移动期间的差值
      var disX = this.data.startX - moveX;
      var delBtnWidth = this.data.delBtnWidth;
      var txtStyle = "";
      if (disX == 0 || disX < 0) { //如果移动距离小于等于0，文本层位置不变
        txtStyle = "left:0px";
      } else if (disX > 0) { //移动距离大于0，文本层left值等于手指移动距离
        txtStyle = "left:-" + disX + "px";
        if (disX >= delBtnWidth) {
          //控制手指移动距离最大值为删除按钮的宽度
          txtStyle = "left:-" + delBtnWidth + "px";
        }
      }
      //获取手指触摸的是哪一项
      var index = e.currentTarget.dataset.index;
      var list = this.data.contactlist;
      list[index].txtStyle = txtStyle;
      //更新列表的状态
      this.setData({
        contactlist: list
      });
    }
  },

  touchE: function(e) {
    if (e.changedTouches.length == 1) {
      //手指移动结束后水平位置
      var endX = e.changedTouches[0].clientX;
      //触摸开始与结束，手指移动的距离
      var disX = this.data.startX - endX;
      var delBtnWidth = this.data.delBtnWidth;
      //如果距离小于删除按钮的1/2，不显示删除按钮
      var txtStyle = disX > delBtnWidth / 2 ? "left:-" + delBtnWidth + "px" : "left:0px";
      //获取手指触摸的是哪一项
      var index = e.currentTarget.dataset.index;
      var list = this.data.contactlist;
      list[index].txtStyle = txtStyle;
      //更新列表的状态
      this.setData({
        contactlist: list
      });
    }
  },

  //获取元素自适应后的实际宽度
  getEleWidth: function(w) {
    var real = 0;
    try {
      var res = wx.getSystemInfoSync().windowWidth;
      var scale = (750 / 2) / (w / 2); //以宽度750px设计稿做宽度的自适应
      // console.log(scale);
      real = Math.floor(res / scale);
      return real;
    } catch (e) {
      return false;
      // Do something when catch error
    }
  },

  initEleWidth: function() {
    var delBtnWidth = this.getEleWidth(this.data.delBtnWidth);
    this.setData({
      delBtnWidth: delBtnWidth
    });
  },

  //点击删除按钮事件
  delItem: function(e) {
    //获取列表中要删除项的下标
    var index = e.currentTarget.dataset.index;
    var list = this.data.contactlist;
    //移除列表中下标为index的项
    const that = this
    var url = "/chat_api/del";
    var params = {
      uid: app.globalData.userInfo.id,
      id: list[index].room_id,
      // uid:app.globalData.userInfo.id
    }

    app.HttpGetSend(url, params, function(res) {
      if (res.msg != "success") {
        app.showTipMsg(res.msg);
      } else {
        app.showTipMsg('删除成功');
        list.splice(index, 1);
        that.setData({
          contactlist: list
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    var that = this;
    clearInterval(that.data.setInter);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    var that = this
    // wx.closeSocket()
    that.data.sk.close();
    wx.onSocketClose(function() {
      console.log('Socket关闭11');
      clearInterval(that.data.setInter);
    });
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    if (selectedNews == true) {
      var that = this;
      // 显示加载图标  
      wx.showLoading({
        title: '玩命加载中',
      })
      // 页数+1  
      that.getContactList();

    } else {
      wx.hideLoading();
    }
  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }
})